from GenerateRandomData.GenInt import GenInt
from GenerateRandomData.GenEmail import GenEmail
from GenerateRandomData.GenName import GenName
from Utils.read_config import read_config
import re
import random

class SqlParser:

    def __init__(self, sql):
        self.sql = sql
        self.fun = ["GenName", "GenEmail", "GenInt"]
    
    def parse(self):
        param = ""
        param_list = []
        param_tag = []
        for index, c in enumerate(self.sql):
            if c == "!":
                param_tag.append(index)
                for i in range(index + 2, len(self.sql)):
                    if self.sql[i] == "}":
                        break
                    param += self.sql[i]
                param_list.append(param)
                param = ""
        return param_list

    def replace_sql(self):
        param_list = self.parse()
        for index, param in enumerate(param_list):
            if param not in self.fun:
                if "[" in param:
                    l = self.translate_str_to_list(param)
                    param_list[index] = l

        values = []
        for index, param in enumerate(param_list):
            values.append(self.translate_cmd_to_value(param))

        for index, v in enumerate(values):
            if isinstance(v, int):
                values[index] = str(v)
            elif isinstance(v, str):
                values[index] = '"' + v + '"'

        return values
            
    def translate_cmd_to_value(self, cmd):
        if cmd == "GenName":
            return GenName().generate_name_sex()["name"]
        elif cmd == "GenEmail":
            return GenEmail().generate_email(GenName().generate_name_sex()["name"])
        elif "GenInt" in cmd:
            nums = [int(s) for s in re.findall(r'\b\d+\b', cmd)]
            return GenInt().generate_int(nums[0], nums[1])
        elif isinstance(cmd, list):
            return random.choice(cmd)

    def translate_str_to_list(self, s):
        l = s.split(",")
        cmd = ""
        cmd_list = []
        for i in l:
            for c in i:
                if c != "[" and c != "]" and c != " " and c != '"':
                    cmd += c
            cmd_list.append(cmd)
            cmd = ""
        return cmd_list

if __name__ == "__main__":
    sql = read_config()["sql"]["sql"]
    print(sql)
    sql_parser = SqlParser(sql)
    param_list = sql_parser.parse()
    res = sql_parser.replace_sql()
    print(res)